<?php

class Controller extends View {

	public $autoRender = true;

	public $useDB = false;

	public $filters;

	public $doNotInit = false;

	public $langs = array(
		"de" => "Deutch",
		"sr" => "Srpski",
		"en" => "English"
	);

	public function __construct() {
		$this->init();
		parent::__construct();
	}

	public function init() {
		// load dbModel
		if($this->useDB !== false){
			$class = is_bool($this->useDB) ? get_class($this) : $this->useDB;
			$class = is_array($class) ? $class : array($class);
			foreach($class as $c){
				$this->dbLoad($c);
			}
		}

		// load language specific strings
		if(isset($this->request->named["lang"])) {
			$_SESSION["language"] = strtolower($this->request->named["lang"]);
			$url = preg_replace('/\/lang\;[a-z]{2}/', '', $_SERVER["REQUEST_URI"]);
			$url = empty($url) ? "/" : $url;
			redirect($url);
		}elseif(empty($_SESSION["language"])){
			$_SESSION["language"] = DEFAULT_LOCALE;
		}
	}

	public function dbLoad($class){
		$modelName = "db".$class;
		if(!$this->$modelName){
			$modelClassName = "Db".$class;
			$this->$modelName = new $modelClassName();
		}
	}

	public function flashMessage($force=false){
		$ret = false;
		if(!empty($_SESSION["flash-message"])){
			$this->set("flash_message", $_SESSION["flash-message"]);
			$this->set("flash_class", $_SESSION["flash-class"]);
			$ret = $this->fetch("flash");

			unset($_SESSION["flash-message"]);
			unset($_SESSION["flash-class"]);
		}
		return $ret ? $ret : ($force ? $this->fetch("flash"): "");
	}

	public function flashSet($message, $class=""){
		$_SESSION["flash-message"] = $message;
		$_SESSION["flash-class"] = $class;
	}

	public function is_active($link){
		$req = Dispatcher::_loadRequest($link);
		if(!$this->request){
			$this->request = (Object)Dispatcher::_loadRequest();
		}

		return $req["controller"] == $this->request->controller && $req["action"] == $this->request->action && array_diff($req["params"],$this->request->params)===array();
	}

	public function breadcrumbs_add($name, $link=""){
		$_SESSION["breadcrumbs"][] = array("name"=>$name, "link"=>$link);
	}
	public function breadcrumbs($name, $link=""){
		return $_SESSION["breadcrumbs"];
	}
}

?>